<?php
namespace backend\controllers;
use yii\web\Controller;
use yii;
use backend\models\User;
use yii\helpers\Url;
/*
 * Created by PhpStorm.
 * User: 张思鸣
 * Date: 2015/12/16
 * Time: 20:13
 * 通过邮箱发送邮件来修改密码
 */
class ResetController extends Controller{
    private $email="qd_flockedcoating@163.com";
    public $layout = "login";
    public function actionIndex(){
        $info='';
        if(isset($_GET['reset'])){
            echo $_GET['reset'];
        }
        if(isset($_POST['email'])==$this->email){
            $resetget=sha1(time().rand(10,100));
            $jsonArray=array(
                'resetData'=>$resetget,
                'expires'=>time()+60*30,
            );
            file_put_contents('./reset.json',json_encode($jsonArray));
            if($_POST['email']==$this->email){
                $mail= Yii::$app->mailer->compose();
                $mail->setTo('qd_flockedcoating@163.com');
                $mail->setSubject("网站密码修改");
                $mail->setHtmlBody("<p>请点击下面的加密连接修改密码，有效时间30分钟！</p>http://localhost/qiche/backend/web/index.php?r=reset/update/&reset={$resetget}");    //发布可以带html标签的文本
                if($mail->send()){
                    $info='邮件发送成功请进入邮箱设置密码';
                }
            }else{
                $info='邮箱填写错误！';
            }
        }
        return $this->render('index',['info'=>$info]);
    }
    public function actionUpdate(){
        $info='';
        if(isset($_GET['reset'])){
            $time=time();
            $data=json_decode(file_get_contents('reset.json'),true);
            if($time > $data['expires']){
                $info='加密连接已经超时，请<a href='.Url::to(['reset/index']).'>[重新填写邮箱]</a>获取！';
            }else{
                if(isset($_POST['user'])){
                    $user=$_POST['user'];
                    $password1=$_POST['password1'];
                    $password2=$_POST['password2'];
                    if(!empty($user) && $password1==$password2 && !empty($password1)){
                        $data=User::find()->where(['id'=>1])->one();
                        $data->password=strtoupper(sha1($password1));
                        $data->user=$user;
                        if($data->save()){
                            $info='密码修改成功，<a href='.Url::to(['login/index']).'>[点击这里]</a> 进行登陆';
                        }
                    }else{
                        $info='用户名不得为空，两次密码必须一致。';
                    }
                }
            }
        }else{
            return $this->redirect(['login/index']);
        }
        return $this->render('update',['info'=>$info]);
    }
}
